package com.shiyipicture.shiyipicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class FilePictureUpload extends FileManagerTemplate{
  @Override
  protected void processFile(Object inputSource, File file) throws IOException {

    MultipartFile multipartFile = (MultipartFile) inputSource;
      multipartFile.transferTo(file);
  }

  @Override
  protected String getOriginalFileName(Object inputSource) {

    MultipartFile multipartFile = (MultipartFile) inputSource;
    return multipartFile.getOriginalFilename();
  }

  @Override
  protected void validPicture(Object inputSource) {
    MultipartFile multipartFile = (MultipartFile) inputSource;
    ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR,"参数不能为空");
    long size = multipartFile.getSize();
    final long ONE_M = 1024 * 1024L;
    ThrowUtils.throwIf(size > 2 * size,ErrorCode.PARAMS_ERROR,"图片大小不能超过2MB");
    String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
    final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpg","jpeg","png","webg");
    ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"图片格式不正确");
  }
}
